package vn.edu.saigontech.ncms.web.ajaxtags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.ajaxtags.servlets.BaseAjaxServlet;
import net.sourceforge.ajaxtags.xml.AjaxXmlBuilder;

import org.hibernate.Session;
import org.hibernate.Transaction;

import vn.edu.saigontech.ncms.model.bookstore.ItemTitle;
import vn.edu.saigontech.ncms.model.program.Program;
import vn.edu.saigontech.ncms.service.ItemTitleService;
import vn.edu.saigontech.ncms.service.ProgramService;
import vn.edu.saigontech.ncms.util.HibernateUtil;

@SuppressWarnings("serial")
public class ProgramTitleSearchServlet extends BaseAjaxServlet {

	@Override
	public String getXmlContent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String programId = request.getParameter("programId");
		AjaxXmlBuilder xml = new AjaxXmlBuilder();
		Session session = null;
		Transaction trans = null;
		List<ItemTitle> titles = new ArrayList<ItemTitle>();
		try {
			session = HibernateUtil.getCurrentSession();
			trans = session.beginTransaction();
			Program program = ProgramService.INSTANCE.findById(Long.parseLong(programId));
			titles = ItemTitleService.INSTANCE.findByProgram(program);
			trans.commit();
		} catch (Exception ex) {
			if (trans != null) {
				trans.rollback();
			}
		} finally {
			if (session != null) {
				session.close();
			}
		}
		xml.addItem("", true, "");
		for (ItemTitle title : titles) {
			xml.addItem(title.getTitle() + " (" + title.getLevelsName() + ")", true, title.getId().toString());
		}
		return xml.toString();
	}

}
